<template>
  <el-select
    v-model="innerValue"
    placeholder="请选择课程类型"
    @change="handleChange"
  >
    <el-option-group
      v-for="group in groupOptions"
      :key="group.label"
      :label="group.label"
    >
      <el-option
        v-for="item in group.options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      ></el-option>
    </el-option-group>
  </el-select>
</template>

<script>
  import { getCourseTypeByPage } from '@/apis/courseType'

  const ENU_COURSE_TYPE_CATEGORY = {
    1: '体育类',
    2: '棋类',
    3: '文艺类',
    4: '书画类',
    99: '其他',
  }

  export default {
    props: {
      value: {
        type: [String, Number],
        default: null,
      },
    },
    data() {
      return {
        innerValue: null,
        groupOptions: [],
      }
    },
    async created() {
      this.innerValue = this.value
      const { list } = await getCourseTypeByPage()
      list.forEach((item) => {
        const group = this.getGroupByCategory(item.classtype)

        if (group) {
          group.options.push({
            label: item.className,
            value: item.id,
          })
        } else {
          this.groupOptions.push({
            id: item.classtype,
            label: ENU_COURSE_TYPE_CATEGORY[item.classtype] || '未知类型',
            options: [
              {
                label: item.className,
                value: item.id,
              },
            ],
          })
        }
      })
    },
    methods: {
      getGroupByCategory(category) {
        return this.groupOptions.find((d) => d.id === category)
      },
      handleChange() {
        this.$emit('input', this.innerValue)
      },
    },
  }
</script>
